function [hfile, mi, mn1, mn2, mn3] = srf_MarkSpikes(hfile, hfile2, cutoff, varargin)
% SRF::MarkSpikes  - find spiked vertices (1-based indices)
%
% FORMAT:       [srf, sps, npmin, vdmin, vdmean] = srf.MarkSpikes([spikesrf, co]);
%
% Input fields:
%
%       spikesrf    srf object to determine spikes from (smoothed SRF)
%       co          simply passed as cutoff to SRF::FindSpikes
%
% Output fields:
%
%       srf         colored SRF
%       sps         Vx1 vertex list of found spikes
%       npmin       Vx1 minimal product list per vertex
%       vdmin       Vx1 min vertex-to-neighbors distance
%       vdmean      Vx1 mean vertex-to-neighbors distance
%
% See also @BVQXfile/private/srf_FindSpikes

% Version:  v0.7g
% Build:    9100721
% Date:     Oct-07 2009, 9:46 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% check arguments
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'srf')
    error( ...
        'BVQXfile:BadArguments', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);

% special case: information given!
numvert = bc.NrOfVertices;
if nargin > 4 && ...
    isa(hfile2, 'double') && ...
    isa(cutoff, 'double') && ...
    isa(varargin{1}, 'double') && ...
    isa(varargin{2}, 'double') && ...
    numel(hfile2) == numvert && ...
    numel(cutoff) == numvert && ...
    numel(varargin{1}) == numvert && ...
    numel(varargin{2}) == 1 && ...
   ~isinf(varargin{2}) && ...
   ~isnan(varargin{2}) && ...
    varargin{2} > 0 && ...
    varargin{2} < 1
    mn1 = hfile2;
    mn2 = cutoff;
    mn3 = varargin{1};
    cutoff = varargin{2};
    mi = find( ...
        (mn1 .* (mn2 / mean(mn2)) .* (mn3 / mean(mn3))) <= cutoff);
    
% continue normally
else
    
    % second SRF given
    if nargin < 2 || ...
        numel(hfile2) ~= 1 || ...
       ~isBVQXfile(hfile2, 'srf')
        hfile2 = hfile;
    else
        bc2 = bvqxfile_getcont(hfile2.L);
        if bc2.NrOfVertices ~= bc.NrOfVertices
            error( ...
                'BVQXfile:BadArgument', ...
                'For multiple SRF objects, NrOfVertices must match.' ...
            );
        end
    end
    if nargin < 3
        cutoff = Inf;
    end

    % get information on secondary SRF
    [mi, mn1, mn2, mn3] = srf_FindSpikes(hfile2, cutoff);
end

% normalize mn1, mn2, mn3 between [0..1]
r1 = [min(mn1), max(mn1) + eps];
r2 = [min(mn2), max(mn2) + eps];
r3 = [min(mn3), max(mn3) + eps];
    
% color srf
vc = zeros(numel(mn1), 4);
vc(mi, 1) = NaN;
vc(:, 2) = fix(32 + 200 * (mn1 - r1(1)) / (r1(2) - r1(1)));
vc(:, 3) = fix(32 + 200 * (mn2 - r2(1)) / (r2(2) - r2(1)));
vc(:, 4) = fix(32 + 200 * (mn3 - r3(1)) / (r3(2) - r3(1)));
bc.VertexColor = vc;
bc.ConvexRGBA = [1/8, 1/8, 1/8, 1];
bvqxfile_setcont(hfile.L, bc);
